package com.timmy.blekit.ui.activitys;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.inuker.bluetooth.library.search.SearchResult;
import com.timmy.blekit.R;
import com.timmy.blekit.adapter.BleDeviceAdapter;
import com.timmy.blekit.presenter.MainActivityPresenter;
import com.timmy.blekit.utils.BleUtil;
import com.timmy.blekit.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    public static final int BLUETOOTH_DISCOVERABLE_DURATION = 6666;
    public static final int REQUEST_CODE_BLUETOOTH_ON = 821;
    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.recycleview)
    RecyclerView mRecyclerView;
    public BleDeviceAdapter mDeviceAdapter;
    private MainActivityPresenter mMainActivityPresenter;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


        mMainActivityPresenter = new MainActivityPresenter(this);

        initRecycleView();
    }

    private void initRecycleView() {

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mDeviceAdapter = new BleDeviceAdapter(null);
        mDeviceAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mDeviceAdapter.isFirstOnly(false);
        mRecyclerView.setAdapter(mDeviceAdapter);

        mDeviceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchResult result = (SearchResult) adapter.getItem(position);
                // Toast.makeText(MainActivity.this, "" + result.getName(), Toast.LENGTH_SHORT).show();

                showProgressDialog("连接蓝牙", "连接中....");
                mMainActivityPresenter.connectDevice(result);

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        // 判断是否拥有定位权限
        isPermissionGranted();
    }

    private void isPermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            MainActivityPermissionsDispatcher.doAacheNeedsPermissionWithCheck(this);
        } else {
            // initBlueTooth();
            mMainActivityPresenter.initBlueTooth();

            if (!Utils.isOPen(this)) {
                showOpenGPSDialog();
            }
        }
    }

    // 弹出打开GPSdialog
    public void showOpenGPSDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("定位未打开");
        dialog.setMessage("您需要在系统设置中打开GPS定位才能使用");
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 点击事件的回调方法
                finish();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 去系统设置页面
                // 转到手机设置界面，用户设置GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 123); // 设置完成后返回到原来的界面
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @OnClick({R.id.btn_scan, R.id.stop_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_scan:
                boolean bluetoothOpened = BleUtil.getInstance().isBluetoothOpened();
                if (!bluetoothOpened) {
                    // 蓝牙未开启,请求是否开启
                    mMainActivityPresenter.openBluetooth();
                } else {
                    // 已经打开, 请求直接扫描蓝牙设备
                    mMainActivityPresenter.scanBluetoothDevice();
                }

                break;
            case R.id.stop_scan:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            if (resultCode == 120) {
                mMainActivityPresenter.scanBluetoothDevice();
                Toast.makeText(this, "开启蓝牙成功", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "开启蓝牙失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // ===================== permission ===============
    @NeedsPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
    void doAacheNeedsPermission() {
        // 处理当用户允许该权限时需要处理的方法
        mMainActivityPresenter.initBlueTooth();
    }

    @OnShowRationale(Manifest.permission.ACCESS_COARSE_LOCATION)
    void ACheShowRationale(PermissionRequest request) {
        // 提示用户权限使用的对话框
        request.proceed();
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_COARSE_LOCATION)
    void AChePermissionDenied() {
        // Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.ACCESS_COARSE_LOCATION)
    void ACacheOnNeverAskAgain() {
        // 被禁止,不再询问
        showDialLog();
    }


    private void showDialLog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("扫描设备需要允许设备获取定位权限, 是否允许?");
        builder.setNegativeButton("去打开", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri packageURI = Uri.parse("package:" + MainActivity.this.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });

        builder.setPositiveButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // finish();
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    public void showProgressDialog(String title, String message) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(MainActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

}
